//
//  BERxRetryExtension.swift
//  BasicExtensions
//
//  Created by 范晓鑫 on 2023/2/28.
//

import RxSwift

extension PrimitiveSequence {
    /// 重试
    /// - Parameters:
    ///   - maxAttemptCount: 重试次数
    ///   - interval: 每次间隔
    ///   - increase: 每次递增间隔(单位与interval一致)
    public func retry(_ maxAttemptCount: Int?, dueTime: RxTimeInterval, increase: Int? = nil) -> PrimitiveSequence<Trait, Element> {
        return self.retry { error in
            var index = 0
            var due = dueTime
            return error.flatMap { er in
                if let maxAttemptCount, index >= maxAttemptCount {
                    return Observable<Int>.error(er)
                }
                if let increase {
                    switch due {
                    case .nanoseconds(let v): due = .nanoseconds(v + increase)
                    case .microseconds(let v): due = .microseconds(v + increase)
                    case .milliseconds(let v): due = .milliseconds(v + increase)
                    case .seconds(let v): due = .seconds(v + increase)
                    default: break
                    }
                }
                index += 1
                return Observable<Int>.timer(due, scheduler: MainScheduler.instance)
            }
        }
    }
}
